package com.snsoft.controller;

import java.io.IOException;
import java.net.URLEncoder;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;

import com.snsoft.bean.User;
import com.snsoft.bean.UserInfo;
import com.snsoft.exception.PasswordError;
import com.snsoft.exception.UserNotFound;
import com.snsoft.service.user.LoginService;
import com.snsoft.service.user.UpdatePasswordService;
import com.snsoft.util.Constants;
import com.snsoft.util.EncodeUtils;
import com.snsoft.util.JsonUtils;

/**
 * 
 * @author 慎伟康
 * 
 * @date 2017年10月21日 下午7:32:06
 * 
 * @Description TODO
 *    user模块控制器
 */
@WebServlet("/user")
public class UserController extends HttpServlet {
	private static final long serialVersionUID = 1L;
    
    public UserController() {
        super();
    }

	/**
	 * 接口分流
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String method = request.getParameter("method");
		if (method != null && method.trim().length() > 0) {
			if("logout".equals(method)){
				this.logout(request, response);
			}
		}else{
			response.getWriter().write(
					JsonUtils.objectToJson(null, Constants.CODE_ERROR, "请求异常！"));
		}
	}
	
	/**
	 * 接口分流
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String method = request.getParameter("method");
		if (method != null && method.trim().length() > 0) {
			if("login".equals(method)){
				this.login(request, response);
			}else if("updatePassword".equals(method)){
				this.updatePassword(request, response);
			}
		}else{
			response.getWriter().write(
					JsonUtils.objectToJson(null, Constants.CODE_ERROR, "请求异常！"));
		}
	}

	/**
	 * 登录接口
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void login(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//校验参数
		if(StringUtils.isEmpty(request.getParameter("userCode"))){
			response.getWriter().write(
					JsonUtils.objectToJson(null, Constants.CODE_ERROR, "用户账号不能为空！"));
			return;
		}
		if(StringUtils.isEmpty(request.getParameter("userPassWord"))){
			response.getWriter().write(
					JsonUtils.objectToJson(null, Constants.CODE_ERROR, "用户密码不能为空！"));
			return;
		}
		int time = 0;//自动登录时间默认为0
		if(!StringUtils.isEmpty(request.getParameter("time"))){
			time = Integer.parseInt(request.getParameter("time"));
		}
		
		//获取用户
		User user = null;
		LoginService ls = new LoginService();
		try {
			user = ls.getUser(request.getParameter("userCode"));
		} catch (UserNotFound e) {
			response.getWriter().write(
					JsonUtils.objectToJson(null, Constants.CODE_ERROR, "该用户不存在！"));
			return;
		} catch (SQLException e) {
			response.getWriter().write(
					JsonUtils.objectToJson(null, Constants.CODE_ERROR, Constants.JSON_ERROR));
			return;
		}
		
		//校验密码
		if(user != null){
			if(!EncodeUtils.encodeByMd5(request.getParameter("userPassWord"))
					.equals(user.getUserPassWord())){
				response.getWriter().write(
						JsonUtils.objectToJson(null, Constants.CODE_ERROR, "密码错误！"));
				return;
			}
		}
		
		//密码正确，写入session
		request.getSession(true).setAttribute("userInfo", 
				new UserInfo(user.getUserID(), user.getUserName(), user.getRole()));
		
		//拼接账号和密码，URL编码解决中文乱码
		String userInfo = URLEncoder.encode(user.getUserCode() + "_"
				+ EncodeUtils.encodeByBase64(user.getUserPassWord()), Constants.CHARSET);
		Cookie cookie = new Cookie("userInfo", userInfo);
		cookie.setMaxAge(60 * 60 * 24 * time);//设置cookie有效期
		response.addCookie(cookie);

		response.getWriter().write(
				JsonUtils.objectToJson(user, Constants.CODE_SUCCESS, "登录成功！"));
	}
	
	/**
	 * 登出接口
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void logout(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		HttpSession session = request.getSession(false);
		if(session != null){
			//移除session
			session.removeAttribute("userInfo");
			//设置cookie失效
			Cookie cookie = new Cookie("userInfo", "");
			cookie.setMaxAge(0);
			response.addCookie(cookie);
		}
		
		response.sendRedirect(request.getContextPath() + "/index.html");
	}
	
	/**
	 * 修改密码接口
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void updatePassword(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//校验参数
		if(StringUtils.isEmpty(request.getParameter("oldPassWord"))){
			response.getWriter().write(
					JsonUtils.objectToJson(null, Constants.CODE_ERROR, "旧密码不能为空！"));
			return;
		}
		if(StringUtils.isEmpty(request.getParameter("newPassWord1"))){
			response.getWriter().write(
					JsonUtils.objectToJson(null, Constants.CODE_ERROR, "新密码1不能为空！"));
			return;
		}
		if(StringUtils.isEmpty(request.getParameter("newPassWord2"))){
			response.getWriter().write(
					JsonUtils.objectToJson(null, Constants.CODE_ERROR, "新密码2不能为空！"));
			return;
		}
		if(!request.getParameter("newPassWord1").equals(request.getParameter("newPassWord2"))){
			response.getWriter().write(
					JsonUtils.objectToJson(null, Constants.CODE_ERROR, "新密码不一致！"));
			return;
		}
		
		//获取用户session
		HttpSession session = request.getSession(false);
		if(session == null){//判断用户是否登录
			response.getWriter().write(
					JsonUtils.objectToJson(null, Constants.CODE_NOT_LOGIN, Constants.JSON_NOT_LOGIN));
			return;
		}else{
			UserInfo userInfo = (UserInfo)session.getAttribute("userInfo");
			if(userInfo == null){
				response.getWriter().write(
						JsonUtils.objectToJson(null, Constants.CODE_NOT_LOGIN, Constants.JSON_NOT_LOGIN));
				return;
			}
			
			//调用业务方法
			UpdatePasswordService ups = new UpdatePasswordService();
			try {
				ups.updatePassword(userInfo.getUserID(), request.getParameter("oldPassWord"), request.getParameter("newPassWord1"));
			} catch (SQLException e) {
				response.getWriter().write(
						JsonUtils.objectToJson(null, Constants.CODE_ERROR, "修改失败！"));
				return;
			} catch (UserNotFound e) {
				response.getWriter().write(
						JsonUtils.objectToJson(null, Constants.CODE_ERROR, "该用户不存在！"));
				return;
			} catch (PasswordError e) {
				response.getWriter().write(
						JsonUtils.objectToJson(null, Constants.CODE_ERROR, "旧密码错误！"));
				return;
			}
		}
		
		response.getWriter().write(
				JsonUtils.objectToJson(null, Constants.CODE_SUCCESS, "修改成功！"));
	}

}
